package com.aicare99.flutter_plugin_print;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
import android.util.Log;

import androidx.annotation.NonNull;

import com.printer.sdk.PrinterConstants;
import com.printer.sdk.PrinterInstance;
import com.printer.sdk.usb.USBPort;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;

/**
 * FlutterPluginPrintPlugin
 */
public class FlutterPluginPrintPlugin implements FlutterPlugin, MethodCallHandler {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private MethodChannel channel;

    private Context mContext;
    public static PrinterInstance myPrinter;
    private static UsbDevice mUSBDevice;
    private List<UsbDevice> deviceList;
    private static final String ACTION_USB_PERMISSION = "com.android.usb.USB_PERMISSION";

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
        channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "flutter_plugin_print");
        channel.setMethodCallHandler(this);

        mContext = flutterPluginBinding.getApplicationContext();
//        Log.i("AAA", "嗨嗨嗨");
        UsbManager mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> devices = mUsbManager.getDeviceList();
        deviceList = new ArrayList<UsbDevice>();
        for (UsbDevice device : devices.values()) {
            if (USBPort.isUsbPrinter(device)) {
                deviceList.add(device);
            }
        }
        if (deviceList.isEmpty()) {
            Toast.makeText(mContext, "小票打印机链接失败", Toast.LENGTH_LONG).show();
        } else {
            mUSBDevice = deviceList.get(0);
            myPrinter = PrinterInstance.getPrinterInstance(mContext, mUSBDevice, null);
            if (mUsbManager.hasPermission(mUSBDevice)) {
                //连接一次
                myPrinter.openConnection();

//                Log.e("AAAAAAAAAAAAAAAAAAAAAAA", String.valueOf(PrinterConstants.paperWidth));

//                //初始化多次
//                myPrinter.initPrinter();
//
//                myPrinter.setPrinter(Command.ALIGN, Command.ALIGN_CENTER);
//                myPrinter.setFont(0, 1, 1, 0, 0);
//                myPrinter.printText("测试店名\n");
//
//                myPrinter.setPrinter(Command.ALIGN, Command.ALIGN_LEFT);
//                myPrinter.setFont(0, 0, 0, 0, 0);
//                myPrinter.printText("嗨嗨嗨");

            } else {
                Toast.makeText(mContext, "没有打印机权限", Toast.LENGTH_LONG).show();
                // 没有权限询问用户是否授予权限
                PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0,
                        new Intent(ACTION_USB_PERMISSION), 0);
                IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
                filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
                filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
                mUsbManager.requestPermission(mUSBDevice, pendingIntent); // 该代码执行后，系统弹出一个对话框
            }
        }


    }

    @Override
    public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
        switch (call.method) {
            case "getPlatformVersion":
                result.success("Android " + android.os.Build.VERSION.RELEASE);
                break;
            case "DEMO":
                XTUtils.demo(myPrinter);
                result.success(true);
                break;
            case "PRINT_TEXT":
                String text = call.argument("text");
                XTUtils.printText(myPrinter, text);
                result.success(true);
                break;
            case "HALF_CUT":
                XTUtils.halfCut(myPrinter);
                result.success(true);
                break;
            case "ALL_CUT":
                XTUtils.allCut(myPrinter);
                result.success(true);
                break;
            case "SET_FONT":
                Integer mCharacterType = call.argument("mCharacterType");
                Integer mWidth = call.argument("mWidth");
                Integer mHeight = call.argument("mHeight");
                Integer mBold = call.argument("mBold");
                Integer mUnderline = call.argument("mUnderline");
                XTUtils.setFont(myPrinter, mCharacterType, mWidth, mHeight, mBold, mUnderline);
                result.success(true);
                break;
            case "ALIGN_LEFT":
                XTUtils.alignLeft(myPrinter);
                result.success(true);
                break;
            case "ALIGN_RIGHT":
                XTUtils.alignRight(myPrinter);
                result.success(true);
                break;
            case "ALIGN_CENTER":
                XTUtils.alignCenter(myPrinter);
                result.success(true);
                break;
            case "NEW_LINE":
                Integer line = call.argument("line");
                XTUtils.newLine(myPrinter, line);
                result.success(true);
                break;
            case "INIT":
                XTUtils.init(myPrinter);
                result.success(true);
                break;
            default:
                result.notImplemented();
                break;
        }
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        channel.setMethodCallHandler(null);
    }

//  private Handler mHandler = new Handler(Looper.getMainLooper()) {
//    @SuppressLint("ShowToast")
//    @Override
//    public void handleMessage(Message msg) {
//
//    }
//  }
}
